package com.lwj.project1.RecommendPageFragments;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.project1.R;
import com.lwj.project1.databaseHelper.MySqliteOpenHelper;
import com.lwj.project1.entity.GameCard;
import com.lwj.project1.entity.GameCategory;

import java.util.ArrayList;
import java.util.List;


public class AmericanFragment extends Fragment {

    private ViewPager viewPager;
    // 桌游轮播图的图片
    private int[] mImg;
    // 设置桌游轮播图的图片id
    private int[] mImg_id;
    // 桌游轮播图的标题
    private String[] mDec;

    private ArrayList<ImageView> mImgList;
    private LinearLayout american_linear;
    private TextView carousel_title;
    // 展示桌游卡片的listView
    private ListView gameShowBox;
    private int previousSelectedPosition = 0;
    boolean isRunning = false;
    private boolean flag = true;
    private List<GameCard> gameCards;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_american, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);
        gameCards = new ArrayList<>();
        initLoopView(view);
        MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(view.getContext());
        List<GameCategory> gameCategories = mySqliteOpenHelper.findGameCategoryByModel("AMERICAN");
        if (gameCategories == null || gameCategories.size() < 0)return;

        for (int i = 0;i < gameCategories.size();i++){
            GameCard gameCard = new GameCard(gameCategories.get(i).getGameCategoryImg(),gameCategories.get(i).getGameCategoryName(),gameCategories.get(i).getGameCategoryDescription());
            gameCards.add(gameCard);
        }
        MyGameAdapter myGameAdapter = new MyGameAdapter(view.getContext(), gameCards);
        gameShowBox.setAdapter(myGameAdapter);
        gameShowBox.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(view.getContext(),ShowGameInfoActivity.class);
                intent.putExtra("img",gameCards.get(position).getImg());
                intent.putExtra("model","AMERICAN");
                intent.putExtra("name",gameCards.get(position).getGameName());
                intent.putExtra("description",gameCards.get(position).getGameIntroduction());
                startActivity(intent);
            }
        });

    }
    private void initLoopView(View view) {
        viewPager = view.findViewById(R.id.american_carousel);
        american_linear = view.findViewById(R.id.dots);
        carousel_title = view.findViewById(R.id.carousel_title);
        gameShowBox = view.findViewById(R.id.game_show_box);

        // 图片资源id数组
        mImg = new int[]{
                R.drawable.a_1,
                R.drawable.a_2,
                R.drawable.a_3,
                R.drawable.a_4,
                R.drawable.zero2
        };

        // 文本描述
        mDec = new String[]{
                "文化冲突",
                "诡镇奇谈",
                "深海谍影",
                "疯狂诡宅",
                "我的老婆"
        };

        mImg_id = new int[]{
                R.id.a_pager_img1,
                R.id.a_pager_img2,
                R.id.a_pager_img3,
                R.id.a_pager_img4,
                R.id.a_pager_img5
        };

        // 初始化要展示的5个ImageView
        mImgList = new ArrayList<>();
        ImageView imageView;
        View dotView;
        LinearLayout.LayoutParams layoutParams;
        // 设置图片和导航点
        for (int i = 0; i < mImg.length; i++) {
            //初始化要显示的图片对象
            imageView = new ImageView(view.getContext());
            imageView.setBackgroundResource(mImg[i]);
            imageView.setId(mImg_id[i]);
            imageView.setOnClickListener(new LoopViewClickListener(getActivity().getApplicationContext()));
            mImgList.add(imageView);
            //加引导点
            dotView = new View(view.getContext());
            dotView.setBackgroundResource(R.drawable.dot);
            layoutParams = new LinearLayout.LayoutParams(10, 10);
            if (i != 0) {
                layoutParams.leftMargin = 10;
            }
            //设置默认所有都不可用
            dotView.setEnabled(false);
            american_linear.addView(dotView, layoutParams);
        }
        // 默认选中第一个导航点
        american_linear.getChildAt(0).setEnabled(true);
        carousel_title.setText(mDec[0]);
        previousSelectedPosition = 0;
        //设置适配器
        viewPager.setAdapter(new LoopViewAdapter(mImgList));
        // 把ViewPager设置为默认选中Integer.MAX_VALUE / t2，从十几亿次开始轮播图片，达到无限循环目的;
        int m = (Integer.MAX_VALUE / 2) % mImgList.size();
        int currentPosition = Integer.MAX_VALUE / 2 - m;
        viewPager.setCurrentItem(currentPosition);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                // 这边也要进行设置 不然会连续跳转
            }

            @Override
            public void onPageSelected(int i) {
                int newPosition = i % mImgList.size();
                carousel_title.setText(mDec[newPosition]);
                american_linear.getChildAt(previousSelectedPosition).setEnabled(false);
                american_linear.getChildAt(newPosition).setEnabled(true);
                previousSelectedPosition = newPosition;
            }

            @Override
            public void onPageScrollStateChanged(int i) {
                switch (i){
                    case ViewPager.SCROLL_STATE_IDLE:
                        flag = true;break;
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        flag = false;break;
                }
            }
        });

        // 开启轮询
        new Thread() {
            public void run() {
                isRunning = true;
                while (isRunning) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //下一条
                    if (flag)getActivity().runOnUiThread(() -> viewPager.setCurrentItem(viewPager.getCurrentItem() + 1));
                }
            }
        }.start();
    }
}